//
//  FPluginFakeView.m
//  FFoundation
//
//  Created by 三井 on 2019/10/30.
//

#import "FPluginFakeView.h"
#import "NSObject+FPlugin.h"
#import "FPluginWrappedData.h"
#import "NSObject+FPluginData.h"
#import "FPluginHost.h"

@interface FPluginFakeView ()

@property (nonatomic, strong) NSMutableArray *fakeDatas;
@property (nonatomic, readonly) UIView *sourceView;

@end

@implementation FPluginFakeView

- (NSMutableArray *)plg_datas {
    if (self.fakeDatas) {
        return self.fakeDatas;
    } else {
        return self.pluginHost.datas;
    }
}

@synthesize update = _update;
- (BOOL)plg_beginUpdate {
    BOOL rs = YES;
    if (![self.sourceView isFake]) {
        rs = [self.sourceView plg_beginUpdate];
    }
    _update = rs;
    
    if (self.isUpdating && self.fakeDatas) {
        return self.fakeDatas;
    }
    
    self.fakeDatas = [NSMutableArray array];
    if (rs) {
        for (FPluginWrappedData *data in self.sourceView.plg_datas) {
            if ([data isKindOfClass:FPluginWrappedData.class] && [data.from isEqualToString:[[self.plugin class] identifier]]) {
                [self.fakeDatas addObject:data.object];
            } else {
                [self.fakeDatas addObject:[NSNull null]];
            }
        }
    }
    
    return rs;
}

- (void)plg_endUpdate {
    _update = NO;
    
    NSMutableArray *mArr = self.sourceView.plg_datas;
    
    /// 将原有的该插件放入的数据删除
    for (NSInteger i = mArr.count - 1; i >= 0; i--) {
        FPluginWrappedData *data = mArr[i];
        if ([(NSObject *)[data plugin] isEqualPlugin:self.plugin]) {
            [mArr removeObjectAtIndex:i];
        }
    }
    /**
     将不同的数据写回到数据集合中
     */
    for (NSInteger i = 0; i < self.fakeDatas.count; i++) {
        NSObject * data = [self.fakeDatas objectAtIndex:i];
        NSObject * oriData = nil;   // 原数据对应位置
        if (i < mArr.count) {
            oriData = mArr[i];
        }
        
        if (![data isKindOfClass:NSNull.class] && ![oriData.object isEqual:data]) {
            [mArr insertObject:[FPluginWrappedData wrapObject:data for:self.plugin] atIndex:i];
        }
    }
    
    [self.fakeDatas removeAllObjects];
    self.fakeDatas = nil;
    
    [self.sourceView plg_endUpdate];
}

- (UIView *)sourceView {
    return (UIView *)self.source;
}

@end
